
import com.mit.web.business.proxy.DesignProxy;
import com.mit.web.business.remote.IInvokeResponder;
import com.mit.web.config.Constants;
import com.mit.web.config.SizeGroupConfig;
import com.mit.web.event.PopWinCloseEvent;
import com.mit.web.util.FlexUtil;
import com.mit.web.util.LogUtil;
import com.mit.web.util.MessageUtil;
import com.mit.web.util.Validator;
import com.mit.web.view.component.monitor.IProgressMonitor;
import com.mit.web.view.design.StyleDetailPanelD;
import com.mit.web.vo.design.StyleVO;

import flash.events.MouseEvent;
import flash.geom.Point;

import mx.controls.Alert;
import mx.controls.DataGrid;
import mx.core.UIComponent;
import mx.events.CloseEvent;
import mx.events.FlexEvent;
import mx.logging.ILogger;
import mx.resources.ResourceManager;
import mx.rpc.events.ResultEvent;
import mx.utils.StringUtil;

private var _styleId:int;
private var _logger:ILogger;
[Bindable]private var _style:StyleVO = new StyleVO();
private var _proxy:DesignProxy = DesignProxy.getInstance();
private var _pm:IProgressMonitor;


public function set styleId(id:int):void{
	_styleId = id;
}


private function init():void{
	
	_logger = LogUtil.getLogger(this);
	
	if(_styleId > 0){
		//Retrieve Style
		var responder:IInvokeResponder = _proxy.getStyleById(_styleId);
		responder.addResultListener(loadStyleHandler);
		responder.addFaultListener(exceptionHandler);
	}else{
		_logger.debug("new Style");
		
		//TODO 目前只有一组尺码组。如果多个的时候，要让用户自己选尺码组
		var sizeGroup:String =  "WOMEN_01";
		_style.sizeGroup = sizeGroup;
		_style.sampleSize = SizeGroupConfig.getInstance().getSampleSize(sizeGroup);
		_style.specInd = Constants.NO;
		
		//默认为今年
		_style.creationDate = new Date();
		_style.year = (new Date()).fullYear;
		
		bundleSources();
	}		
}

private function loadStyleHandler(event:ResultEvent):void{
	_style = event.result as StyleVO;
	//还原从SIZE DATA FIELDS 到 尺码组
	_style.sizes = SizeGroupConfig.getInstance().getSelectedSizes(_style.sizeGroup, _style.sizeFields);

	bundleSources();
	
	//设置approve button 
	if(_style.dressState == Constants.CLOSE && _style.state != Constants.STYLE_STATE_APPR)
		btn_app.enabled = true;
	
}

/**
 * 给window中的必要组件绑定数据源
 * */
private function bundleSources():void{
	//给Tab绑定数据
	panel_a.style = _style;
	panel_b.style = _style;
	panel_c.source = _style.primaryFab;
	panel_d.source = _style.secondaryFab;
}



private function deleteConfirmHandler():void{

		var rsp:IInvokeResponder = _proxy.deleteStyle(_style.id);
		rsp.addResultListener(deleteResultHandler);
		rsp.addFaultListener(exceptionHandler);

}

private function deleteResultHandler(event:ResultEvent):void{
	var e:PopWinCloseEvent = new PopWinCloseEvent(PopWinCloseEvent.DELETED);	
	e.msg = ResourceManager.getInstance()
		.getString(Constants.BUNDLE_COMMON,"info.common.deleted",[_style.code]);
	this.dispatchEvent(e);
	closeWindow(this);	
}

private function doApprove():void{
	var rsp:IInvokeResponder = _proxy.approveStyle(_style.id);
	rsp.addResultListener(approveResultHandler);
	rsp.addFaultListener(exceptionHandler);
}



private function approveResultHandler(event:ResultEvent):void{
	var e:PopWinCloseEvent = new PopWinCloseEvent(PopWinCloseEvent.APPROVED);	
	e.msg = ResourceManager.getInstance()
		.getString(Constants.BUNDLE_COMMON,"info.common.approved",[_style.code]);
	this.dispatchEvent(e);
	closeWindow(this);	
}



private function terminateConfirmHandler(event:CloseEvent):void{

		var rsp:IInvokeResponder = _proxy.terminateStyle(_style.id);
		rsp.addResultListener(terminateResultHandler);
		rsp.addFaultListener(exceptionHandler);

}

private function terminateResultHandler(event:ResultEvent):void{
	var e:PopWinCloseEvent = new PopWinCloseEvent(PopWinCloseEvent.TERMINATED);	
	e.msg = ResourceManager.getInstance()
		.getString(Constants.BUNDLE_COMMON,"info.common.terminated",[_style.code]);
	this.dispatchEvent(e);
	closeWindow(this);	
}

private function doSave(event:Event):void{
	

	//验证
	if(!validate())
		return;
	
	assembleVO();
	
	//Call Save with progress bar
	var responder:IInvokeResponder = _proxy.saveStyle(_style).installProgressBar(_pm, this);
	responder.addFaultListener(exceptionHandler);
	responder.addResultListener(savedHandler);
	
}

private function savedHandler(event:ResultEvent):void{
	var e:PopWinCloseEvent;
	if(_style.id > 0){
		e = new PopWinCloseEvent(PopWinCloseEvent.SAVED);
	}else{
		e = new PopWinCloseEvent(PopWinCloseEvent.CREATED);
	}
	_style = event.result as StyleVO;	
	e.msg = ResourceManager.getInstance()
		.getString(Constants.BUNDLE_COMMON,"info.common.saved",[_style.code]);
	this.dispatchEvent(e);
	closeWindow(this);	
}

//将页面元素组装到VO中
private function assembleVO():void{
	_style.year = parseInt(panel_a.lst_year.selectedItem);
	_style.season = panel_a.lst_season.selectedId;
	_style.prodTypeId = panel_a.lst_prdType.selectedId;
	_style.name = panel_a.txt_name.text;
	_style.gift = panel_a.lst_gift.selectedItem;
	_style.designerId = panel_a.lst_dsgn.selectedId;
	_style.sampleSize = panel_a.lst_sampleSize.selectedItem;
	_style.sizes = panel_a.lst_sizes.selectedSize;
	_style.estimatedFee = panel_a.txt_fee.number;
	_style.sizeFields = SizeGroupConfig.getInstance().getSelectedDataFields(_style.sizeGroup, _style.sizes);
	_style.colors = panel_a.lst_color.selectedColor;
	_style.remarks = panel_a.txt_rmk.text;
	//有更新图像的话，使用新附件
	if(panel_a._uploader.wrappedFileName)
		_style.img = panel_a._uploader.wrappedFileName;
	
	
	_style.specInd = panel_b.style.specInd;
	_style.specialReq = panel_b.style.specialReq;
	_style.technicalReq = panel_b.style.technicalReq;
	_style.endReq = panel_b.style.endReq;
	
	_style.primaryFab = panel_c.source;
	
	_style.secondaryFab = panel_d.source;
	
}

private function validate():Boolean{
	var rtn:Boolean = true;
	//Panel A
	if(panel_a.lst_season.selectedIndex == -1){
		tab_form.selectedIndex = 0;
		showRequiredErrorTip(panel_a.lst_season);
		rtn = false;
	}
	if(rtn && panel_a.lst_prdType.selectedIndex == -1){
		tab_form.selectedIndex = 0;
		showRequiredErrorTip(panel_a.lst_prdType);
		rtn = false;
	}
	if(rtn && Validator.isNullOrBlank(panel_a.txt_name.text)){
		tab_form.selectedIndex = 0;
		showRequiredErrorTip(panel_a.txt_name);
		rtn = false;
	}
	if(rtn && panel_a.lst_color.selectedColor.length == 0){
		tab_form.selectedIndex = 0;
		showRequiredErrorTip(panel_a.lst_color);
		rtn = false;
	}
	//Panel B
	//如果是新建的，该页面没去的时候，肯定不会出这个错误。
	//否则，panel B已经实例化，就可以应用到其中的对象了
	if(rtn && panel_b.style.specInd == Constants.YES
		&& Validator.isNullOrBlank(panel_b.style.technicalReq)){
		tab_form.selectedIndex = 1;
		showRequiredErrorTip(panel_b.txt_tech);
		rtn = false;
	}
	//Panel c
	if(rtn){
		if(panel_c.source.length == 0){
			tab_form.selectedIndex = 2;
			//不能用这种提示方式是因为panel C中的对象可能还没create。无法引用
			//showVerticalRequiredErrorTip(panel_c.dg);
			var requiredMsg:String = ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"error.common.requiredSpecifiedField",["主料清单"]);			
			MessageUtil.popSystemInfo(requiredMsg,null);
			rtn = false;
		}else{
			//这种情况只会在Panel已经修改过才会发生，所以里面的datagrid对象肯定已经实例化了。
			for(var row:int = 0; row < panel_c.source.length;row++){
				if(Validator.isNullOrBlank(panel_c.source[row].name)){
					tab_form.selectedIndex = 2;
					showVerticalRequiredErrorTip(panel_c.dg);
					panel_c.dg.editedItemPosition = {columnIndex:1, rowIndex:row};
					rtn = false;
					break;
				} 
			}
		}
	}
	//Panel d
	if(rtn){
		if(panel_d.source.length == 0){
			tab_form.selectedIndex = 3;
			//showVerticalRequiredErrorTip(panel_d.dg);
			var requiredMsg:String = ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"error.common.requiredSpecifiedField",["辅料清单"]);			
			MessageUtil.popSystemInfo(requiredMsg,null);
			rtn = false;
		}else{
			for(var row:int = 0; row < panel_d.source.length;row++){
				if(Validator.isNullOrBlank(panel_d.source[row].name)){
					tab_form.selectedIndex = 3;
					showVerticalRequiredErrorTip(panel_d.dg);
					panel_d.dg.editedItemPosition = {columnIndex:1, rowIndex:row};
					rtn = false;
					break;
				} 
			}
		}	
	}
	return rtn;
}


